<?php 
use Illuminate\Support\Facades\Event;
class WalletController extends CenterController{

	protected $orderService;

	public function __construct(OrderService $orderService)
	{
			$this->orderService = $orderService;
	}
	/**
	 * 显示钱包充值界面
	 */
	public function walletMoneyIn() {
		$wallet = Wallet::getWallet();
		if (Route::is('center.lawyer.wallet.moneyin')) {
			$this->layout = View::make('layouts.lawyercenter');
		}
		$this->makeView('center.wallet.moneyin',['money' => $wallet->money]);
	}
	
	/**
	 * 显示钱包提现界面
	 */
	public function walletMoneyOut() {
		$wallet = Wallet::getWallet();
		if (Route::is('center.lawyer.wallet.moneyout')) {
			$this->layout = View::make('layouts.lawyercenter');
		}
		$this->makeView('center.wallet.moneyout',['money' => $wallet->money]);
	}
	
	/**
	 * 显示送心意界面
	 */
	public function walletReward($user_id){
		$data = [];
		$wallet = Wallet::getWallet();
		$data['money'] = round($wallet->money);
		$data['user_id'] = $user_id;
		$data['count'] = WalletTransaction::rewardCount($user_id);
		return $this->makeView('center.customer.question.complete_sxy', $data);
	}
	
	//充值
// 	public function recharge(){
// 		$posts = Input::all();
// 		$rules = array (
// 				'money' => 'required|integer|between:0,100000000'
		
// 		);
// 		$messages = array(
// 				'money.required' => '请输入充值金额',
// 				'money.integer' => '请输入整数金额',
// 				'money.between' => '您输入的金额不合法'
// 		);
// 		$validator = Validator::make ( $posts, $rules, $messages );
// 		if ($validator->fails()) {
// 			// the given data did not pass validation
// 			return $this->makeView(
// 					'errors.400',
// 					$validator->errors(),
// 					400
// 			);
// 		}
// 		try{
// 			//微信支付返回成功状态后
// 			$order_id = '1234567';
// 			$message = "微信充值";
// 			$wallet = Wallet::getWallet();
// 			$wallet->money = $wallet->money +$posts['money'];
// 			DB::transaction(function() use($wallet,$order_id, $posts, $message) {
// 				$wallet->save();
// 				$myWalletTransaction = WalletTransaction::createRecharge(Auth::user()->id, $order_id, $posts['money'], $message, WalletTransaction::STATUS_SUCCESS);
// 			});
// 			$wallet->save();
// 		}catch(exception $ex){
// 			Log::error($ex);
// 			return $this->makeView('errors.503','服务器没有暂时没有反应,请稍后再试',503);
// 		}
// 		return $this->makeView('general.201', ['money' => $wallet->money], 201);
		
// 	}

	/**
	 * 显示我的钱包界面
	 */
	public function myWallet(){
		$wallet = Wallet::getWallet();
		
		if (Route::is('center.lawyer.wallet')) {
			$this->layout = View::make('layouts.lawyercenter');
		}
		return $this->makeView('center.wallet.wallet', array('money' => round($wallet->money)), 200);
	}
	
	/**
	 * 显示我的钱包账目
	 */
	public function rechargeRecord(){
		
		$input = Input::all();
		$page = Input::get('page', 1);
		$type = Input::get('type', '');
		$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
		$offset = ($page-1) * $rows_per_page;
		$order = Input::get('order', 'latest');
		$orderby = 'created_at';
		$direction = 'DESC';
		if ($order == 'chronological') {
			$direction = 'ASC';
		}
		
		$rules = array (
				'page' => 'numeric|min:1',
				'rows_per_page' => 'numeric|min:1'
				
		);
		$messages = array(
				'page.numeric' => 'page需要是数字',
				'rows_per_page.numeric' => 'rows_per_page需要是数字',
		);
		$validator = Validator::make ( $input, $rules, $messages );
		if ($validator->fails()) {
			// the given data did not pass validation
			return $this->makeView(
					'errors.400',
					$validator->errors(),
					400
			);
		}
		$query = WalletTransaction::where('user_id',Auth::user()->id);
		if($type){
			$query = $query->where('type', $type);
		}
		$records = $query->take($rows_per_page)->skip($offset)->orderBy($orderby, $direction)->get();
		$data = [];
		foreach($records as $record){
			$data[] = $record->getRecord();
		}
		Log::info(__METHOD__ . __LINE__ . json_encode($data));
		 return $this-> makeView('general.200', $data);
	}
	
	/**
	 * 钱包提现操作
	 */
	public function withdraw(){
		$posts = Input::all();
		Validator::extend ( 'balance', function ($attr, $value, $parameters) use ($posts) {
			return Wallet::balance($posts['money']);
		});
		$rules = array (
				'money' => 'required|integer|balance|between:0,1000000',
				'user_name' => 'required',
				'brank_name' => 'required',
				'card_id' => 'required|numeric',
				'contact_phone' => 'required'
		);
		$messages = array(
				'money.required' => '请填写提现金额',
				'money.integer' => '提现金额需为整数',
				'money.balance' => '余额不足',
				'money.between' => '提现金额不合法',
				'user_name.required' => '请填写用户真实姓名',
				'brank_name.required' => '请填写开户行',
				'card_id.required' => '请填写银行卡号',
				'card_id.numeric' => '银行卡号不合法',
				'contact_phone.required' => '请填写联系方式'
		);
		$validator = Validator::make($posts, $rules, $messages );
		if($validator->fails()) {
			return $this->makeView('errors.400', $validator->errors(),400);
		}
		
		try{
				$wallet = Wallet::getWallet();
				$wallet->money = $wallet->money - $posts['money'];
				$wallet->save();
				$withdraw = WalletWithdraw::_createWithdraw($posts);
				$message = "提现到".$posts['brank_name']."卡";
				$record = WalletTransaction::createWithdraw($withdraw['id'], $posts['money'], $message);			
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '服务请暂时无法响应，请稍后再试', 503);
		}
		Event::fire('waller_money_out_user_bankcard');
		return $this->makeView('general.200', ['money' =>$wallet->money], 200);
	}

	/**
	 * 钱包送心意操作
	 */
	public function reward(){
		$posts = Input::all();
		Validator::extend ( 'balance', function ($attr, $value, $parameters) use ($posts) {
			return Wallet::balance($posts['money']);
		});
		$rules = array (
				'order_id' => 'required',
				'user_id' => 'required|exists:lawyer,user_id',
				'money' => 'required|balance|integer|between:0,1000000'
		);
		$messages = array(
				'user_id.required' => '请选择律师',
				'order_id.required' => 'order_id必须',
				'user_id.exists' => '该律师不存在',
				'money.integer' => '请输入整数金额',
				'money.required' => '请输入金额',
				'money.balance' => '余额不足',
				'money.between' => '您输入的金额不合法'
		);
		$validator = Validator::make ( $posts, $rules, $messages );
		if ($validator->fails()) {
			return $this->makeView('errors.400', $validator->errors(), 400);
		}
		// 验证成功
		try {
			$message = [];
			$lawyerName = User::find($posts['user_id'])->realname;
			$myWallet = Wallet::find(Auth::user()->id);
			$myWallet->money = $myWallet->money - $posts['money'];
			$lawyerWallet = Wallet::find($posts['user_id']);
			if(!$lawyerWallet){
				$lawyerWallet = new Wallet();
				$lawyerWallet->user_id = $posts['user_id'];
			}
			$lawyerWallet->money = $lawyerWallet->money + $posts['money'];
			$message['send'] = "送心意给".$lawyerName."律师";
			$message['recive'] = "收到".Auth::user()->realname."的心意";
			DB::transaction(function() use($myWallet,$lawyerWallet, $posts, $message){
				$myWallet->save();
				$lawyerWallet->save();
				//修改订单状态
				$order = $this->orderService->getOrderById($posts['order_id']);
				$order->state = Order::STATE_PAID;
				$order->save();
				$myWalletTransaction = WalletTransaction::createReward(Auth::user()->id, $posts['user_id'], $posts['money'], $message, null, 'wallet');
			});
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
					'errors.503',
					'发表失败，请稍后再试',
					503
			);
		}
		Event::fire('reward', $posts['user_id']);
		return $this->makeView('general.200',['money' => $myWallet->money],200);
	}

}